import React from 'react';
import PropTypes from 'prop-types';
import { Modal } from 'ywen-mobile-ui';
import BaseComponent from '../common/baseComponent.js';
import Loading from '../common/loading';

class BarcodeModal extends BaseComponent {
  static propTypes = {
    code: PropTypes.string,
    barcode: PropTypes.string,
  }

  static defaultProps = {
    code: '',
    barcode: null,
  }
  state = {
    show: false,
    angle: window.orientation + 90,
  }

  componentDidMount() {
    window.addEventListener('orientationchange', this.orientationChanged);
  }

  componentWillUnmount() {
    window.removeEventListener('orientationchange', this.orientationChanged);
  }

  orientationChanged = () => {
    this.setState({
      angle: window.orientation + 90,
    });
  }

  show = () => {
    this.setState({ show: true });
  }

  close = () => {
    this.setState({ show: false });
  }

  render() {
    const { show, angle } = this.state;
    const { code, barcode } = this.props;
    if (!show || !code) {
      return null;
    } else if (!this.props.barcode) {
      return <Loading />;
    }
    const numbers = [];
    for (let index = 0; index < code.length; index += 4) {
      const num = code.substr(index, 4);
      numbers.push(
        <span key={index}>{num}</span>,
      );
    }


    const max = Math.max(window.innerHeight, window.innerWidth);
    const min = Math.min(window.innerHeight, window.innerWidth);
    const style = {
      width: max,
      height: min,
      transform: `rotateZ(${angle}deg)`,
    };
    return (
      <Modal touchFunc={this.close}>
        <div className="full-barcode">
          <div className="container" style={style}>
            <img alt="" src={barcode} />
            <p className="number">{numbers}</p>
          </div>
        </div>
      </Modal>
    );
  }
}

export default BarcodeModal;

